// pages/seek_job/seek_job.js
const app = getApp(), core = require('../../utils/core'), util = require('../../utils/util'),chatIM = require('../../utils/websocket.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    seekJobType: null,
    banners: [],
    current: 0,
    jobList: [],
    jobListMore: {page:1},
    showFilter:false,//显示条件弹出层
    filterTabIndex:0,//条件层tab index

    filterTab1SubIndex: "0",
    filterTab2SubIndex: "-1",
    filterTab3SubIndex: "0",
    selectedDistrict: '',
    query: {benefit_id:[]},

    categories: [],
    subCategories: [],
    districts: [],
    nearbyArr: [1,3,5,7,10],
    hourlySalaryOptions: [],
    dailySalaryOptions: [],
    monthlySalaryOptions: [],
    refreshDayOptions: [3,7,15,30],
  },
  swiperchange: function (e) {
    this.setData({
      current: e.detail.current
    })
  },
  swiperTextchange: function (e) {
    this.setData({
      text_current: e.detail.current
    })
  },
  tab:function(event) {
    if(this.data.showFilter && this.data.filterTabIndex==event.currentTarget.dataset.index) {
      this.hideFilter();
    }else {
      this.setData({showFilter: true, filterTabIndex: event.currentTarget.dataset.index});
      wx.setNavigationBarColor({
        frontColor: '#000000', // 必写项
        backgroundColor: '#ffffff', // 必写项
        animation: { // 可选项
          duration: 400,
          timingFunc: 'easeIn'
        }
      });
    }
  },
  hideFilter() {
    this.setData({showFilter:false});
    wx.setNavigationBarColor({
      frontColor: '#ffffff', // 必写项
      backgroundColor: '#ff7100', // 必写项
      animation: { // 可选项
        duration: 400,
        timingFunc: 'easeIn'
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let page = this;
    var query = wx.createSelectorQuery();
    query.select('.tab').boundingClientRect(function (res) {
      page.setData({
        offset_top:res.top
      })
    }).exec();
    this.setData({currentCity: app.getCurrentCity()});
    // this.refreshPage();
	app.eventBus.on(app.Events.CurrentCityChange, this.eventOnCurrentCityChange, this);
	//未读消息
	if (app.globalData.chat_config.SocketTask) {
		chatIM.setMessageBadge(false)
	 }
	app.eventBus.on(app.Events.WebsocketMessageCount, this.eventWebsocketMessageCount,this);
  },
  onUnload: function () {
	app.eventBus.off(app.Events.CurrentCityChange, this.eventOnCurrentCityChange);
	app.eventBus.off(app.Events.WebsocketMessageCount, this.eventWebsocketMessageCount);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }

    let seek_job_type = core.getCache('seek_job_type')||'', originSeekJobType = this.data.seekJobType;
    this.setData({seekJobType: seek_job_type});
    if(seek_job_type!==originSeekJobType) {
      this.data.refreshOnShow = true;
    }
    switch (seek_job_type) {
      case 'labour':
        wx.setNavigationBarTitle({title: ''});
        break;
      case 'parttime':
        wx.setNavigationBarTitle({title: '兼职招聘'});
        break;
      case 'redpacket':
        wx.setNavigationBarTitle({title: '红包招聘'});
        break;
      default:
        wx.setNavigationBarTitle({title: '找工作'});
        break;
    }
    if(this.data.refreshOnShow) {
      this.setData({refreshOnShow:false});
      this.refreshPage();
    }
  },
  refresh: function (clearQuery=false) {
    this.setData({jobList:[], jobListMore:{page:1}, showFilter: false});
    if(clearQuery) {
      this.setData({query: {},filterTab1SubIndex: "0", filterTab2SubIndex: "-1", filterTab3SubIndex: "0",});
    }
    this.fetch();
  },
  fetch: function () {
    let query = Object.assign({cate_type: this.data.seekJobType},this.data.query);
    util.fetch(this, '/xilujob.job/lists', query, 'jobListMore', 'jobList', 'data');
  },
  bindResetFormQuery: function () {
    this.setData({
      'query.work_experience_id': '', 'query.type': '', 'query.education_level_id': '', 'query.benefit_id': [], 'query.refresh_days': ''
    });
  },
  bindFormQueryConfirm: function () {
    this.refresh();
  },
  bindTabSubIndexChange: function (event) {
    let param = event.currentTarget.dataset.param, index = event.currentTarget.dataset.index;
    this.setData({[param]: index});
    if(param==='filterTab3SubIndex' && index==='0') {
      //选择薪资类型不限
      this.setData({
        'query.salary_type': '',
        'query.salary_min': '',
        'query.salary_max': '',
        'query.salary_option_id': '',
      });
      this.refresh();
    }
  },
  // 选择一级分类
  bindCategoryPick: function (event) {
    let index = event.currentTarget.dataset.index;
    if(index==-1) {
      //不限分类
      this.setData({
        filterTab2SubIndex: index,
        'query.category_id': '',
        subCategories: [],
      });
      this.refresh();
    }else {
      this.setData({
        filterTab2SubIndex: index,
        subCategories: this.data.categories[index].childlist,
      });
    }
  },
  // 选择二级分类
  bindCategoryChange: function (event) {
    let id = event.currentTarget.dataset.id;
    this.setData({
      'query.category_id': id,
    });
    this.refresh();
  },
  //选择附近
  bindDistanceChange: function(event) {
    if(!this.data.query.pos) {
      wx.showToast({title: '定位失败,请到设置同意授权',icon:'none'});
      return;
    }
    this.setData({
      'query.distance': event.currentTarget.dataset.distance,
      'query.district_id': '',
      'query.town_id': '',
    });
    this.refresh();
  },
  //选择区
  bindDistrictChange: function(event) {
    let district = event.currentTarget.dataset.district;
    
    this.setData({
      'query.district_id': event.currentTarget.dataset.id,
      'filterTab2Name': district?district.name:'不限',
      'query.distance':''
    });

    // this.setData({
    //   'query.district_id': event.currentTarget.dataset.id,
    //   'query.town_id': '',
    //   'filterTab2Name': district?district.name:'不限',
    //   'query.distance':''
    // });
    this.refresh();
  },
  //选择镇
  bindTownChange: function(event) {
    let town = event.currentTarget.dataset.town;
    this.setData({
      'query.town_id': event.currentTarget.dataset.id,
      'query.district_id': '',
      'filterTab2Name': town?town.name:'不限',
      'query.distance':''
    });
    this.refresh();
  },
  //选择薪资
  bindSalaryOptionChange: function (event) {
    this.setData({
      'query.salary_type': event.currentTarget.dataset.type,
      'query.salary_min': event.currentTarget.dataset.min,
      'query.salary_max': event.currentTarget.dataset.max,
      'query.salary_option_id': event.currentTarget.dataset.id,
    });
    this.refresh();
  },
  //
  bindQueryParamChange: function (event) {
    let param = event.currentTarget.dataset.param, value = event.currentTarget.dataset.value,
      multiple = event.currentTarget.dataset.multiple || false;
    if(multiple) {
      if(value=='') {
        this.setData({['query.'+param]:[]});
        return;
      }
      if(!this.data.query[param]) {
        this.data.query[param] = [];
      }
      let index = this.data.query[param].indexOf(value);
      if(index>=0) {
        this.data.query[param].splice(index,1);
      }else {
        this.data.query[param].push(value);
      }
      this.setData({query: this.data.query});
    }else {
      this.setData({['query.'+param]: value});
    }

  },
  eventOnCurrentCityChange: function (currentCity) {
    this.setData({currentCity});
    let pages = getCurrentPages();
    //如果当前页面正在显示, 刷新此页； 否则下次显示时刷新
    if(pages[pages.length-1]===this) {
      this.refreshPage();
    }else {
      this.setData({refreshOnShow: true});
    }
  },
  onPullDownRefresh: function () {
    this.refreshPage();
  },
  refreshPage() {
    let page = this;
    core.get({url:'/xilujob.banner/banners/group/job_index',loading:false,success(ret,response) {page.setData({banners: ret.data});}});
    util.getAreas().then(function(districts) {page.setData({districts: districts});});
    
	util.getJobCategories(2).then(categories=>{page.setData({categories:categories});});

    util.getSalaryOptions(1).then(options=>{page.setData({hourlySalaryOptions:options})});
    util.getSalaryOptions(2).then(options=>{page.setData({dailySalaryOptions:options})});
    util.getSalaryOptions(3).then(options=>{page.setData({monthlySalaryOptions:options})});
    util.getWorkExperienceOptions().then(options=>{page.setData({workExperiences:options})});
    util.getEducationLevels().then(levels=>{page.setData({educationLevels:levels})});
    util.getBenefits().then(benefits=>{page.setData({benefits: benefits})});
    //获取定位
    wx.getLocation({
      success: res => {
        page.setData({'query.pos': res.longitude+','+res.latitude});
      },
      fail: res => {
        console.log(res);
      }
    });
    this.refresh(true);
    wx.stopPullDownRefresh();
  },
  inputQ(e) {
    this.setData({'query.q':e.detail.value.trim()});
  },
  search() {
    this.refresh();
  },
  bindSelectDistrict(e) {
    // let district = e.currentTarget.dataset.district;
    let districts = this.data.districts;
    //console.log(districts)
    this.setData({filterTab1SubIndex: 1, selectedDistrict:districts});
  },

  onShareAppMessage() {

  },

  eventWebsocketMessageCount(data){
	var list = this.getTabBar().data.list;
	list[1].megNum = app.globalData.chat_config.messageCount;
	this.getTabBar().setData({
	  list
	})
  },

});
